<?php

namespace app\rent\controller\Business;

use think\Controller;
use app\common\library\Email;
use think\Db;
use think\Request;

class Base extends Controller
{
    protected $BusinessModel = null;
    protected $CollectionModel = null;


    public function __construct()
    {
        parent::__construct();


        $this->BusinessModel = model('Business.Business');
        $this->CollectionModel = model('Business.Collection');
    }

    public function index()
    {
        $busid = $this->request->param('busid', 0, 'trim');

        $ProductCount = $this->CollectionModel->where(['busid' => $busid, Db::raw('proid Is Not Null')])->count();
        $CollCount = $this->CollectionModel->where(['busid' => $busid, Db::raw('cateid Is Not Null')])->count();
        $OrderCount = model('Product.Lease')->where(['busid' => $busid])->count();

        $this->success('查询成功', null, ['ProductCount' => $ProductCount, 'CollCount' => $CollCount, 'OrderCount' => $OrderCount]);
    }

    // 我的收藏页面
    public function collection()
    {
        // 获取URL值
        $action = $this->request->param('action', '', 'trim');;

        // 获取客户id
        $busid = $this->request->param('busid', 0, 'trim');

        // 获取分页页码
        $page = $this->request->param('page', 1, 'trim');

        // 获取搜索关键字
        $keyword = $this->request->param('keyword', '', 'trim');

        // 每页显示数据
        $limit = 6;

        $start = ($page - 1) * $limit;

        $list = null;
        if ($action === 'product') {
            $where = [
                'busid' => ['=', $busid],
                Db::raw('proid Is Not Null')
            ];
            if ($keyword !== '') {
                $where['name'] =  ['like', "%$keyword%"];
            }
            $list = $this->CollectionModel->where($where)->with(['product'])->order('createtime', 'desc')->limit($start, $limit)->select();
            // exit($this->CollectionModel->getLastSql());
        }

        if ($action === 'category') {
            $where = [
                'busid' => ['=', $busid],
                Db::raw('cateid Is Not Null')
            ];
            if ($keyword !== '') {
                $where['name'] =  ['like', "%$keyword%"];
            }
            $list = $this->CollectionModel->where($where)->with(['category'])->order('createtime', 'desc')->limit($start, $limit)->select();
            // exit($this->CollectionModel->getLastSql());
        }

        if ($list) {
            $this->success('查询数据成功', null, $list);
        } else {
            $this->error('暂无数据', null, []);
        }
    }

    public function register()
    {
        $mobile = $this->request->param('mobile', '', 'trim');
        $password = $this->request->param('password', '', 'trim');

        $sourceid = model('Business.Source')->where(['name' => '租赁平台'])->value('id');

        $salt = build_ranstr();

        $password = md5($password . $salt);

        // 封装数据
        $data = [
            'mobile' => $mobile,
            'password' => $password,
            'salt' => $salt,
            'invitecode' => build_ranstr(),
            'sourceid' => $sourceid
        ];

        $result = $this->BusinessModel->validate('common/Business/Business')->save($data);

        if ($result === FALSE) {
            $this->error($this->BusinessModel->getError());
        } else {
            $this->success('注册成功');
        }
    }

    public function login()
    {
        $mobile = $this->request->param('mobile', '', 'trim');
        $password = $this->request->param('password', '', 'trim');

        $business = $this->BusinessModel->where(['mobile' => $mobile])->find();

        if (!$business) {
            $this->error('用户不存在');
        }

        $password = md5($password . $business['salt']);

        if ($password != $business['password']) {
            $this->error('密码错误');
        }

        $this->success('登录成功', null, $business);
    }

    public function profile()
    {
        $params = $this->request->param();

        $business = $this->BusinessModel->find($params['busid']);

        if (!$business) {
            $this->error('用户不存在');
        }

        // 封装更新数据
        $data = [
            'id' => $params['busid'],
            'nickname' => $params['nickname'],
            'gender' => $params['gender']
        ];

        // 修改邮箱
        if (!empty($params['email'])) {
            if ($params['email'] != $business['email']) {
                $data['email'] = $params['email'];
                $data['auth'] = 0;
            }
        }

        // 修改密码
        if (!empty($params['password'])) {
            $salt = build_ranstr();
            $password = md5($params['password'] . $salt);

            $data['password'] = $password;

            $data['salt'] = $salt;
        }

        // 头像
        if (!empty($_FILES['avatar']) && $_FILES['avatar']['size'] > 0) {
            $avatar = build_upload('avatar');

            if ($avatar['code'] === 0) {
                $this->error($avatar['msg']);
            }

            $data['avatar'] = $avatar['data'];
        }

        // 地区
        $code = !empty($params['code']) ? $params['code'] : '';
        $parentpath = model('Region')->where(['code' => $code])->value('parentpath');

        if (!$parentpath) {
            $this->error('选择地区不存在');
        }

        [$province, $city, $district] = explode(',', $parentpath);

        $data['province'] = $province;

        $data['city'] = $city;

        $data['district'] = $district;

        $result = $this->BusinessModel->isUpdate(true)->save($data);

        if ($result === FALSE) {
            if (isset($data['avatar']) && $_FILES['avatar']['size'] > 0) {
                @is_file('.' . $data['avatar']) && @unlink('.' . $data['avatar']);
            }

            $this->error('修改资料失败');
        } else {
            if (isset($data['avatar']) && $_FILES['avatar']['size'] > 0) {
                @is_file('.' . $business['avatar']) && @unlink('.' . $business['avatar']);
            }

            $Business = $this->BusinessModel->find($params['busid']);

            $this->success('修改资料成功', null, $Business);
        }
    }

    public function send()
    {
        $email = $this->request->param('email', '', 'trim');

        $busid = $this->request->param('id', 0, 'trim');

        $business = $this->BusinessModel->where(['id' => $busid, 'email' => $email])->find();

        if (!$business) {
            $this->error('邮箱不存在');
        }

        // 生成验证码
        $code = build_ranstr(4);

        $Ems = model('Ems')->where('email', $email)->find();

        // 开启事务
        Db::startTrans();

        if ($Ems) {
            $data = [
                'id' => $Ems['id'],
                'event' => '邮箱认证',
                'email' => $email,
                'code' => $code,
                'times' => $Ems['times'] + 1,
                'ip' => $this->request->ip()
            ];

            $result = model('Ems')->isUpdate(true)->save($data);
        } else {
            $data = [
                'event' => '邮箱认证',
                'email' => $email,
                'code' => $code,
                'times' => 1,
                'ip' => $this->request->ip()
            ];

            $result = model('Ems')->validate('common/Ems')->save($data);
        }

        if ($result === FALSE) {
            model('Ems')->rollback();
            $this->error(model('Ems')->getError());
        }

        // 实例化发送邮件类
        $Mail = new Email();

        // 邮件内容
        $content = "
            <h1>欢迎新用户！云平台认证</h1>
            您的验证码为：<b>$code</b>
        ";

        // 发送人
        $FromEmail = config('site.mail_from');

        $SendStatus = $Mail->from($FromEmail, '云平台')->subject('云平台邮箱验证')->message($content)->to($email)->send();

        if ($result == true && $SendStatus == true) {
            Db::commit();
            $this->success('发送成功');
        } else {
            Db::rollback();
            $this->error($Mail->getError());
        }
    }
}
